package com.ticket.sass.provider.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 对特殊字符进行转义
 * @author ywb
 * @date 2021-12-06 16:38
 */
public class EscapeUtil {
    
    public final static DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public final static DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");
    
    public static String escapeChar(String str) {
        if (!StringUtils.isEmpty(str)) {
            str = str.replaceAll("\\\\\"", "\""); // 替换成双引号
            str = str.replaceAll("\"", "");
        }
        return str;
    }

    public static String prefixStr(String str, String prefixStr){
        String outPut = "";
        if (!StringUtils.isEmpty(str)) {
            outPut = prefixStr + str;
        }
        return outPut;
    }
    
    public static String postStr(String str, String postStr){
        return StringUtils.isEmpty(str) ? "" : str + postStr;
    }
    
    public static String emptyStr(String str){
        return StringUtils.isEmpty(str) ? "" : str;
    }
    
    public static String dateTimeStr(LocalDateTime dateTime){
        if (Objects.isNull(dateTime)){
            return "";
        }
        return DATE_TIME_FORMATTER.format(dateTime);
    }
    
    public static String dateTimeStr(LocalDateTime dateTime, DateTimeFormatter formatter){
        if (Objects.isNull(dateTime)){
            return "";
        }
        return formatter.format(dateTime);
    }
    
    public static LocalDateTime stringToLocalDateTime(String time) {
        return LocalDateTime.parse(time, DATE_TIME_FORMATTER);
    }
    
    public static String dateStr(LocalDateTime dateTime){
        if (Objects.isNull(dateTime)){
            return "";
        }
        return DATE_FORMATTER.format(dateTime);
    }
    
    public static Map<Object, Object> toJson(Object jumpConfig)   {
        Map<Object, Object> map;
        try{
            Gson gson = GsonUtil.getInstance();
            map = gson.fromJson(
                jumpConfig.toString(),
                new TypeToken<HashMap<Object, Object>>(){}.getType()
            );
        }catch (Exception exception){
            map = new HashMap<>(0);
        }
        return map;
    }
    
    public static String errorMessage(String field, String message) {
        return String.format("错误来源字段：【%s】, 错误字段提示【%s】", field, message);
    }
    
    
}